package no.ntnu.fp.server;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

import no.ntnu.fp.model.SuperPackage;
import no.ntnu.fp.net.co.Connection;
import nu.xom.Document;
import nu.xom.ParsingException;
import nu.xom.ValidityException;

public class Server {
	
	private ServerListener serverListener;
	private List<ConnectionHandler> clients;
	
	public Server() {
		
		clients = new LinkedList<ConnectionHandler>();
		serverListener = new ServerListener(this);
		
		startListener();
	}
	
	public void addClient(Connection c) {
		
		clients.add(new ConnectionHandler(c, this));
	}
	
	public void dataFromClient(String s, ConnectionHandler sourceClient) {
		System.out.println(s);
		
		nu.xom.Builder parser = new nu.xom.Builder(false);
		nu.xom.Document doc = null;
		try {
			doc = parser.build(s, "");
		} 
		catch (ValidityException e) {} 
		catch (ParsingException e) {} 
		catch (IOException e) {}
		
		SuperPackage sp = new SuperPackage(doc);
		
		/*
		 * TODO: Databasestuffz;
		 */
		
		notifyModelChanged(s, sourceClient);
		
	}
	
	private void notifyModelChanged(String s, ConnectionHandler sourceClient) {
		
		for (ConnectionHandler client : clients) {
			
			if (client != sourceClient) {
				client.send(s);
			}
		}
	}
	
	private void startListener() {
		
		new Thread(serverListener).start();
	}
	
	
}
